import React, { PropTypes, Component } from 'react';
import { Link } from 'react-router'
import { getAuthShop } from './../publicAPI/publicAPI'
import style from './AssistantInput.css';
import { myAjaxJson, myAjaxGet, ROOTURL } from './../publicAPI/publicAPI';




export default React.createClass({
	getInitialState: function() {
		return {
		    assistantName: '',
		    shopsForAdm:[],
		    assistant: [],
		    isChanged: false,
		    //初始化
		    name: '',
            phone: '',
            shop: 'null',
            isUse: false,
            isAssigned: false,
		};
	},

	componentWillMount: function() {
		var _this = this;
		getAuthShop(null, function(data) {
			//console.log(data);
			var shopsForAdm = [];
			let shopsId = {};
			data.forEach((shopMes) => {
				shopsForAdm.push(shopMes.dname);
				shopsId[shopMes.dname] = shopMes.id;
			}); 
			console.log(shopsForAdm);
			this.setState({
				shopsForAdm: shopsForAdm,
				shopsId: shopsId,
			});
		}.bind(_this));
		

	},
	componentDidMount: function() {
		if(this.props.params.id) {
			this.handleGetInfo();
		}
	},
	//有id传进来时调用，获取id详细信息
	handleGetInfo: function() {
            var _this = this;
            var param= {
                id:this.props.params.id
            }
          
            //获取某个理发师助理的详细信息
			myAjaxGet(ROOTURL + 'user/barber-assist/instance.api', param, function(data) {
				console.log(data);
				this.setState({
                    name: data.meta.name,
                    phone: data.meta.phone,
                    shop: data.meta.shop,
                    isUse: data.meta.isUse,
                    isAssigned: data.meta.isAssigned,
                })
			}.bind(_this), function(error) {
				console.log('请求失败');
			})
	},

	handleSubmit: function() {
		let _this = this;
			
		//判断信息是否填写完整
		if(!this.refs.assName.value||!this.refs.shopSelect.value) {
			alert('门店和助理名称不能为空!');
			return
		}
			//get方法获取理发师助理信息
			//理发师助理添加接口，通过这个接口录入
			let param = {};
			this.props.params.id? param.id = this.props.params.id : '';
			console.log(param.id);
			param.dname = this.refs.assName.value;
			param.dd = false;
			//param.stLoginable = true;
			param.meta = {
				name: this.refs.assName.value,
                shop: this.refs.shopSelect.value,
                phone: this.refs.assPhone.value,
                isUse: this.refs.enabled1.checked,
                isAssigned: this.refs.enabled2.checked,
			}
			console.log(param);
			myAjaxJson(ROOTURL + 'user/barber-assist/instance.api', 'POST', param, function(data3) {
				let _this = this;
				console.log(data3);

				//然后通过服务人员扩展信息接口编写相应扩展信息
                var param2 = {};
                //判断是否有Id传入
				this.props.params.id? param2.id = this.props.params.id : param2.servant = data3.id;
				console.log(param2.id); 
				console.log(param2.servant);
				param2.shop = this.state.shopsId[this.refs.shopSelect.value];
				//param2.userid = this.refs.assName.value;
				param2.dd = false;
				param2.meta = {
					name: this.refs.assName.value,
		            shop: this.refs.shopSelect.value,
		            phone: this.refs.assPhone.value,
		            isUse: this.refs.enabled1.checked,
		            isAssigned: this.refs.enabled2.checked,
		            isAssistant: true,
				}
				console.log(param2);
                fetch(ROOTURL +'servant/profile/instance.api', { 
                    method: 'post',
                    //mode: 'cors',
                    headers: { 
                        "Content-type": "application/json; charset=UTF-8" 
                    },
                    body: JSON.stringify(param2) 
                }) 
                .then(function (res) {
                	if(res.ok){
		                res.json().then(function(data) { 
		                	alert('录入成功');   	
		                	console.log(data);
		                	window.location.href = '/SalaryM/AssistantM';
		            	}.bind(_this))
		            } else {
		            	alert('录入失败~~(>_<)~~ ,可能是因为该店铺曾经录入过相同的助理或理发师的名称');
		            }
                }.bind(_this)) 
                .catch(function (error) { 
                    console.log('Request failed', error); 
                });
			}.bind(_this), function(error3) {
				alert('录入失败');
			});
	},

	//选择商店后,理发师助理名字列出
	shopSelect: function() {
		let _this = this;
		let shopSelect = this.refs.shopSelect.value;
		console.log(shopSelect);
		if(shopSelect == '请选择店铺名称') return;
		fetch(ROOTURL +'servant/profile/search.api', { 
            method : 'POST',
            mode: 'cors',
            body: JSON.stringify({})
        })
        .then(res=>{
        	if(res.ok){
                res.json().then(function(data) {    	
                	console.log(data);
		            let assistant = data.filter(function(servantData) {
		            	if((!servantData.dd)&&servantData.meta.isAssistant) {
		            		if(servantData.meta.shop == shopSelect) {
		            			return true
		            		} else return false
		            	} else return false 
		            });
		            console.log(assistant);
		            this.setState({
		            	assistant: assistant,
		            	shop: shopSelect,
		            });
            	}.bind(_this))
            }
        }) 
        .catch(function (error) { 
            console.log('Request failed', error); 
        });
	},

	changeMes: function(val) {
		return (
				<div>
	    			<div className={style["assInput_M"]}>
				    	<p><label>店铺名称：</label>
					    	<select ref="shopSelect" onChange={this.shopSelect}>
					    		<option value="">请选择店铺名称</option>
					    		{
					              this.state.shopsForAdm? this.state.shopsForAdm.map((name, idx) => {
					                return (
					                  <option key={idx} value={`${name}`}>{`${name}`}</option>
					                );
					              }) : ''
					            }
					    	</select>
				    	</p>
					    <p><label htmlFor="assName">助理姓名：</label><input type="text" id="assName" ref="assName" /></p>
				    	<p><label htmlFor="phone">电话：</label>
				    		<input type="text" id="phone" ref="assPhone" />
				    	</p>
				    	<p>
				    		<input 
				    			type="checkbox" 
				    			id="enabled1" 
				    			ref="enabled1"
				    			style={{margin: '0 3px 0 0'}} 
				    		/>
				    		<label htmlFor="enabled1">启用</label>
				    		<input 
				    			type="checkbox" 
				    			id="enabled2" 
				    			ref="enabled2"  
				    			style={{margin: '0 3px 0 30px'}}
				    		/>
				    		<label style={{width: '110px'}} htmlFor="enabled2">是否分配工作</label>
				    	</p>
				    	<button onClick={this.handleSubmit} style={{marginLeft: '0'}} className={style["assInput_button"]}>保存</button>
						<Link to={`/SalaryM/AssistantM`}>
							<button className={style["assInput_button"]}>返回</button>
						</Link>
				    </div>
	    		</div>
		);
	},

	handleKeyPress: function(e) {
	    if(e.which == 13) {
	        this.handleSubmit();
	    }
	},

	render: function() {
		//console.log(this.state.assistant);
		//console.log(this.state.shopsForAdm);
		if(this.props.params.id) {
			return (
				<div className="rt-wrap">
					<div>
						<div className={style["assInput_M"]}>
					    	<p><label>店铺名称：</label>
						    	{this.state.shop}
					    	</p>
						    <p><label>助理姓名：</label>{this.state.name}</p>
					    	<p><label>电话：</label>
					    		{this.state.phone}
					    	</p>
					    	<p>
						    	<input 
							    	type="checkbox" 
							    	checked={this.state.isUse}
							    	style={{margin: '0 3px 0 0'}}
						    	/>
						    	<label>启用</label>
						    	<input 
						    		type="checkbox"  
						    		checked={this.state.isAssigned} 
						    		style={{margin: '0 3px 0 30px'}}
						    	/>
						    	<label style={{width: '110px'}}>是否分配工作</label>	
					    	</p>
					    	<button className={style["assInput_button"]} style={{marginLeft: '0'}} onClick={() => {this.setState({isChanged: true})}}>修改</button>
					    	<Link to={`/SalaryM/AssistantM`}>
								<button className={style["assInput_button"]}>返回</button>
							</Link>
					    </div>
	    			</div>
	    			{
	    				this.state.isChanged? this.changeMes() : ''
	    			}
	    		</div>
			);
		} else {
			//理发师助理录入
			return (
				<div className="rt-wrap">
	    			<div className={style["assInput_M"]}>
				    	<p>
				    		<label>店铺名称：</label>
					    	<select ref="shopSelect" onChange={this.shopSelect}>
					    		<option value="null">请选择店铺名称</option>
					    		{
					              this.state.shopsForAdm? this.state.shopsForAdm.map((name, idx) => {
					                return (
					                  <option key={idx} value={`${name}`}>{`${name}`}</option>
					                );
					              }) : ''
					            }
					    	</select>
				    	</p>
					    <p>
						    <label htmlFor="assName">助理姓名：</label>
						    <input type="text" id="assName" ref="assName" /></p>
				    	<p><label htmlFor="phone">电话：</label>
				    		<input type="text" id="phone" ref="assPhone" />
				    	</p>
				    	<p>
				    		<input 
				    			type="checkbox" 
				    			id="enabled11" 
				    			ref="enabled1" 
				    			style={{margin: '0 3px 0 0'}}
				    		/>
				    		<label htmlFor="enabled11">启用</label>
				    		<input 
				    			type="checkbox" 
				    			id="enabled22" 
				    			ref="enabled2"  
				    			style={{margin: '0 3px 0 30px'}}
				    		/><label style={{width: '110px'}} htmlFor="enabled22">是否分配工作</label>
				    	</p>
						<button className={style["assInput_button"]} style={{marginLeft: '0'}} onClick={this.handleSubmit}>保存</button>
						<Link to={`/SalaryM/AssistantM`}>
							<button className={style["assInput_button"]}>返回</button>
						</Link>
					</div>
					{/*<div>商店已录入的助理:
					    {
					        this.state.assistant[0]? this.state.assistant.map((value, idx) => {
					            console.log(value.userid);
					            return (
					                <p key={idx}>{value.userid}</p>
					            );
					        }) : ''
					    }
					</div>*/}
	    		</div>
			);
		}
	}
});
    
